package com.xnyzc.lhy.mis.service.impl.cms.driver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiniu.util.Json;
import com.xnyzc.lhy.common.component.config.security.TokenUser;
import com.xnyzc.lhy.common.component.convert.DateToStringConverter;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.component.sms.AliCloudSMSUtils;
import com.xnyzc.lhy.common.constant.AliCloudSmsConstant;
import com.xnyzc.lhy.common.constant.RedisPrefixConstant;
import com.xnyzc.lhy.common.entity.Qw;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.DiDiException;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EDiDiErrorCode;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.driver.EAccountStatusType;
import com.xnyzc.lhy.common.penum.driver.EServiceFraction;
import com.xnyzc.lhy.common.penum.driver.ESexType;
import com.xnyzc.lhy.common.penum.driver.info.EOaDUserDriverType;
import com.xnyzc.lhy.common.penum.order.EOrderChannelType;
import com.xnyzc.lhy.common.penum.vehicle.ECallVehType;
import com.xnyzc.lhy.common.penum.vehicle.EvehicleType;
import com.xnyzc.lhy.common.penum.work.EAcceptOrderType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.mis.entity.area.OaSysArea;
import com.xnyzc.lhy.mis.entity.cms.auditentry.OaSysAuditEntry;
import com.xnyzc.lhy.mis.entity.cms.driver.DriverUserInfo;
import com.xnyzc.lhy.mis.entity.cms.driver.DriverVehicleInfo;
import com.xnyzc.lhy.mis.entity.cms.driver.SearchDriverSelect;
import com.xnyzc.lhy.mis.entity.dictionaries.OaSysDict;
import com.xnyzc.lhy.mis.entity.driver.wallet.OaDWallet;
import com.xnyzc.lhy.mis.entity.manager.OaSysManager;
import com.xnyzc.lhy.mis.entity.order.OaCOrderPersonal;
import com.xnyzc.lhy.mis.entity.order.OaDOrder;
import com.xnyzc.lhy.mis.entity.param.cms.PageDTO;
import com.xnyzc.lhy.mis.entity.result.cms.driver.CmsOaDVehicleGpsRes;
import com.xnyzc.lhy.mis.entity.result.cms.veh.VehicleManageInfo;
import com.xnyzc.lhy.mis.entity.result.user.DriverUserResult;
import com.xnyzc.lhy.mis.entity.result.user.OaSysUserRoleRes;
import com.xnyzc.lhy.mis.entity.result.user.UserLoginResult;
import com.xnyzc.lhy.mis.entity.sidebar.OaSysOffice;
import com.xnyzc.lhy.mis.entity.system.OaSysGlobalConfig;
import com.xnyzc.lhy.mis.entity.system.OaSysUser;
import com.xnyzc.lhy.mis.entity.user.OaDUser;
import com.xnyzc.lhy.mis.entity.user.OaDUserInfo;
import com.xnyzc.lhy.mis.entity.user.OaDUserOffice;
import com.xnyzc.lhy.mis.entity.vehicle.OaDDriverVehicle;
import com.xnyzc.lhy.mis.entity.vehicle.OaSysVehicle;
import com.xnyzc.lhy.mis.entity.vehicle.OaSysVehicleMdict;
import com.xnyzc.lhy.mis.feign.amap.IAmapService;
import com.xnyzc.lhy.mis.mapper.area.OaSysAreaMapper;
import com.xnyzc.lhy.mis.mapper.cms.auditentry.OaSysAuditEntryMapper;
import com.xnyzc.lhy.mis.mapper.dictionaries.OaSysDictMapper;
import com.xnyzc.lhy.mis.mapper.driver.wallet.OaDWalletMapper;
import com.xnyzc.lhy.mis.mapper.manager.OaSysManagerMapper;
import com.xnyzc.lhy.mis.mapper.order.OaCOrderPersonalMapper;
import com.xnyzc.lhy.mis.mapper.order.OaDOrderMapper;
import com.xnyzc.lhy.mis.mapper.sidebar.OaSysOfficeMapper;
import com.xnyzc.lhy.mis.mapper.system.OaSysGlobalConfigMapper;
import com.xnyzc.lhy.mis.mapper.system.OaSysUserMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserInfoMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserOfficeMapper;
import com.xnyzc.lhy.mis.mapper.vehicle.OaDDriverVehicleMapper;
import com.xnyzc.lhy.mis.mapper.vehicle.OaSysVehicleMapper;
import com.xnyzc.lhy.mis.mapper.vehicle.OaSysVehicleMdictMapper;
import com.xnyzc.lhy.mis.service.cms.driver.DriverManageService;
import com.xnyzc.lhy.mis.service.cms.util.IOaSysGetOfficeIdListService;
import com.xnyzc.lhy.mis.service.impl.cms.util.OaSysGetOfficeIdListServiceImpl;
import com.xnyzc.lhy.mis.service.impl.cms.vehicle.VehicleManageServiceImpl;
import com.xnyzc.lhy.order.entity.gps.OaDVehicleGps;
import com.xnyzc.lhy.resource.entity.amap.AmapTidParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 司机管理接口实现类
 *
 * @author zhaolijie
 * @date 2019-08-21 19:37
 */
@Service
@Slf4j
public class DriverManageServiceImpl implements DriverManageService {
    private static final String GOSTARTPOINT = "赶赴起点";
    private static final String WAITINGPASSENGER = "等待客人";
    private static final String ONTHEROAD = "行程中";
    private static final String NOTACTION = "听单未执行";
    private static final String IDLESTATE = "空闲中";
    @Autowired
    private IOaSysGetOfficeIdListService iOaSysGetOfficeIdListService;

    @Autowired
    private OaDUserMapper oaDUserMapper;

    @Autowired
    private OaDUserInfoMapper oaDUserInfoMapper;

    @Autowired
    private OaDDriverVehicleMapper oaDDriverVehicleMapper;

    @Autowired
    private OaSysOfficeMapper oaSysOfficeMapper;

    @Autowired
    private OaDUserOfficeMapper oaDUserOfficeMapper;

    @Autowired
    private OaDWalletMapper oaDWalletMapper;
    @Autowired
    private OaSysGlobalConfigMapper oaSysGlobalConfigMapper;

    @Autowired
    private IAmapService iAmapService;

    @Autowired
    private OaSysDictMapper oaSysDictMapper;

    @Autowired
    private OaSysGlobalConfigMapper sysGlobalConfigMapper;

    @Autowired
    private OaSysVehicleMapper oaSysVehicleMapper;

    @Autowired
    private OaSysVehicleMdictMapper oaSysVehicleMdictMapper;

    @Autowired
    private OaSysAreaMapper oaSysAreaMapper;

    @Autowired
    private OaSysGetOfficeIdListServiceImpl oaSysGetOfficeIdListService;

    @Autowired
    private OaCOrderPersonalMapper oaCOrderPersonalMapper;

    @Autowired
    private OaSysManagerMapper oaSysManagerMapper;

    @Autowired
    private OaSysUserMapper oaSysUserMapper;

    @Autowired
    private RedisCommon redisCommon;

    @Autowired
    private OaSysAuditEntryMapper oaSysAuditEntryMapper;

    @Autowired
    private OaDOrderMapper oaDOrderMapper;

    /**
     * 根据司机姓名模糊查询司机id和其供应商信息
     * @param orderNo
     * @return
     */
    @Override
    public Rv queryPersonSearchAsync(String orderNo) {
        long tokenUserId = TokenUtil.getTokenUserId();
        if(CheckUtil.objIsEmpty(tokenUserId,orderNo)){
            throw PangException.create(EErrorCode.missingArg);
        }
        List<OaDOrder> oaDOrders = oaDOrderMapper.selectDOrderList(orderNo);
        if(CheckUtil.objIsEmpty(oaDOrders)){
            return Rv.wrap();
        }
        List<Long> driverIds = oaDOrders.stream().map(item -> item.getDriverId()).collect(Collectors.toList());
        List<DriverUserResult> list = oaDUserMapper.selectDriverByIds(driverIds);
        if(CheckUtil.objIsEmpty(list)){
            return Rv.wrap();
        }
        List<DriverUserResult> resultList = list.stream().map(item -> {
            item.setDriverName(item.getDriverName() + "(" + item.getName() + ")");
            return item;
        }).collect(Collectors.toList());
        return Rv.wrap(resultList);
    }


    /**
     * 将司机添加黑名单或从黑名单恢复
     * @param driverId
     * @param isBlocked
     * @return
     */
    @Override
    public Rv putOrPopDriverBlocklist(Long driverId, Integer isBlocked) {
        if(CheckUtil.allObjIsEmpty(driverId,isBlocked)){
            throw PangException.create(EErrorCode.missingArg);
        }
        //根据司机id跟新黑名单标志
        Integer flag = oaDUserMapper.putOrPopBlocklistByDriverId(driverId,isBlocked);
        if(flag != 1){
            return Rv.error(EErrorCode.addError);
        }
        return Rv.wrap(EErrorCode.success);
    }


    /**
     * 根据司机id查询该司机实时位置经纬度等信息
     * @param driverId
     * @return
     */
    @Override
    public Rv getThisDriverPosition(Long driverId) {
        //根据登录人 进行权限查询
        TokenUser tokenUser = TokenUtil.getTokenUser();
        List<Long> driverIds = getTokenUserOfDriverIds(tokenUser);
        if(CheckUtil.objIsEmpty(driverId)){
            throw PangException.create(EErrorCode.missingArg);
        }
        boolean flag = false;
        for (int i = 0 ;i<driverIds.size();i++){
            if (driverIds.get(i).equals(driverId)){
                flag = true;
            }
        }
        //根据driverId在redis中查询司机实时位置经纬度
        String redisCommonStr = redisCommon.getStr(RedisPrefixConstant.GPS_VEH_KEY_PREFIX + driverId);
        if(flag == true && CheckUtil.strIsNotEmpty(redisCommonStr)){
            OaDVehicleGps oaDVehicleGps = JSON.parseObject(redisCommonStr, OaDVehicleGps.class);
            /*根据driverId和时间查询订单
            从数据库中查询订单号、终点、起点、订单状态、时间*/
            //司机在线且司机接单未执行 acceptanc_order_status == 1
            CmsOaDVehicleGpsRes cmsOaDVehicleGpsRes1 = oaDUserMapper.selectLastPositionByDriverId(driverId);
            //该司机的订单状态为456的
            CmsOaDVehicleGpsRes cmsOaDVehicleGpsRes2 = oaCOrderPersonalMapper.selectDriverPositionByDriverId(driverId);

            if(CheckUtil.objIsNotEmpty(cmsOaDVehicleGpsRes2) && cmsOaDVehicleGpsRes2.getOrderStatus() == 4){
                cmsOaDVehicleGpsRes2.setDriverStatus(GOSTARTPOINT);
                cmsOaDVehicleGpsRes2.setLat(oaDVehicleGps.getLat());
                cmsOaDVehicleGpsRes2.setLng(oaDVehicleGps.getLng());
                return Rv.wrap(cmsOaDVehicleGpsRes2);
            }
            if(CheckUtil.objIsNotEmpty(cmsOaDVehicleGpsRes2) && cmsOaDVehicleGpsRes2.getOrderStatus() == 5){
                cmsOaDVehicleGpsRes2.setDriverStatus(WAITINGPASSENGER);
                cmsOaDVehicleGpsRes2.setLat(oaDVehicleGps.getLat());
                cmsOaDVehicleGpsRes2.setLng(oaDVehicleGps.getLng());
                return Rv.wrap(cmsOaDVehicleGpsRes2);
            }
            if(CheckUtil.objIsNotEmpty(cmsOaDVehicleGpsRes2) && cmsOaDVehicleGpsRes2.getOrderStatus() == 6){
                cmsOaDVehicleGpsRes2.setDriverStatus(ONTHEROAD);
                cmsOaDVehicleGpsRes2.setLat(oaDVehicleGps.getLat());
                cmsOaDVehicleGpsRes2.setLng(oaDVehicleGps.getLng());
                return Rv.wrap(cmsOaDVehicleGpsRes2);
            }
            if(CheckUtil.objIsNotEmpty(cmsOaDVehicleGpsRes1) && CheckUtil.objIsEmpty(cmsOaDVehicleGpsRes2)){
                cmsOaDVehicleGpsRes1.setLat(oaDVehicleGps.getLat());
                cmsOaDVehicleGpsRes1.setLng(oaDVehicleGps.getLng());
                cmsOaDVehicleGpsRes1.setUpdateTime(oaDVehicleGps.getUpdateTime());
                if(cmsOaDVehicleGpsRes1.getAcceptancOrderStatus() == 1){
                    cmsOaDVehicleGpsRes1.setDriverStatus(NOTACTION);
                }else{
                    cmsOaDVehicleGpsRes1.setDriverStatus(IDLESTATE);
                }
                return Rv.wrap(cmsOaDVehicleGpsRes1);
            }
        }
        return Rv.error(EErrorCode.driverNotOnline);
    }

    /**
     * 根据司机姓名和车牌号查询司机信息
     * @param driverName
     * @param vehNo
     * @return
     */
    @Override
    public Rv getDriverInfoByNameAndVehicle(String driverName, String vehNo) {
        //查看当前登录用户查询的权限
        TokenUser tokenUser = TokenUtil.getTokenUser();
        if(CheckUtil.objIsEmpty(tokenUser)){
            throw PangException.create(EErrorCode.missingArg);
        }
        //该用户能查询的运力id
        List<Long> driverIds = getTokenUserOfDriverIds(tokenUser);
        if(CheckUtil.objIsEmpty(driverIds)){
            throw PangException.create(EErrorCode.NotOneDriverOnline);
        }
        if(CheckUtil.objIsEmpty(driverName) && CheckUtil.objIsEmpty(vehNo)){
           throw PangException.create(EErrorCode.missingArg);
        }
        //根据姓名或车牌号查询出司机id以及一些可用信息
       List<OaDVehicleGps> driverList =  oaDUserMapper.selectDriverByNameAndVehicle(driverName,vehNo);
        if(CheckUtil.objIsNotEmpty(driverList)){
            for (OaDVehicleGps oaDVehicleGps:driverList
                 ) {
                for(int i = 0;i<driverIds.size();i++){
                    if(driverIds.get(i).equals(oaDVehicleGps.getDriverId())){
                        return Rv.wrap(driverList);
                    }
                }
            }
        }
        return Rv.wrap();
    }

    /**
     * 查询司机实时位置经纬度等信息
     */
    @Override
    public Rv getAllDriverGPSInfo(){
        //根据登录用户判断角色 再确定查询范围
        TokenUser tokenUser = TokenUtil.getTokenUser();
        if( CheckUtil.objIsEmpty(tokenUser)){
            throw PangException.create(EErrorCode.missingArg);
        }
        List<Long> driverIds = getTokenUserOfDriverIds(tokenUser);
        if(CheckUtil.objIsEmpty(driverIds)){
            throw PangException.create(EErrorCode.NotOneDriverOnline);
        }
        List<HashMap<String, List<OaDVehicleGps>>> oaDVehicleGpsList = getOaDVehicleGps(driverIds);
        return Rv.wrap(oaDVehicleGpsList);
    }

    private  List<HashMap<String, List<OaDVehicleGps>>> getOaDVehicleGps(List<Long> driverIds) {

        List<HashMap<String, List<OaDVehicleGps>>> list = new ArrayList<>();
        //当前APP打开，但是未出车的车辆使用黄色车辆图标
        List<OaDVehicleGps> noActionPositionList = new ArrayList<>();
        //接单状态但未执行订单的车辆，使用绿色图标
        List<OaDVehicleGps> acceptButNoActionPositionList = new ArrayList<>();
        //在任务执行中的车辆，使用蓝色图标
        List<OaDVehicleGps> actioningPositionList = new ArrayList<>();

        //从数据库查询听单未执行的运力、订单状态为4\5\6的运力
        List<CmsOaDVehicleGpsRes> sqlCmsOaDVehicleGpsRes = oaCOrderPersonalMapper.selectDriverPositionList();

        for (int i = 0;i<driverIds.size();i++){
            String redisCommonStr = redisCommon.getStr(RedisPrefixConstant.GPS_VEH_KEY_PREFIX + driverIds.get(i));
            if(CheckUtil.objIsEmpty(redisCommonStr)){
                continue;
            }
            OaDVehicleGps oaDVehicleGps = JSON.parseObject(redisCommonStr, OaDVehicleGps.class);

            if(CheckUtil.objIsEmpty(sqlCmsOaDVehicleGpsRes)){
                noActionPositionList.add(oaDVehicleGps);
                continue;
            }
                for(int j =0;j<sqlCmsOaDVehicleGpsRes.size();j++){
                    CmsOaDVehicleGpsRes driver = sqlCmsOaDVehicleGpsRes.get(j);
                    if(driverIds.get(i).equals(driver.getDriverId())){
                        if(driver.getOrderStatus() == 4 || driver.getOrderStatus() == 5 || driver.getOrderStatus() == 6){
                            actioningPositionList.add(oaDVehicleGps);
                        }else{
                            acceptButNoActionPositionList.add(oaDVehicleGps);
                        }
                        break;
                    }else{
                        if(j==sqlCmsOaDVehicleGpsRes.size()-1){
                            noActionPositionList.add(oaDVehicleGps);
                        }
                    }
                }
        }

        HashMap<String, List<OaDVehicleGps>> positionMap = new HashMap<>();
        positionMap.put("noActionPositionList",noActionPositionList);
        positionMap.put("acceptButNoActionPositionList",acceptButNoActionPositionList);
        positionMap.put("actioningPositionList",actioningPositionList);
        list.add(positionMap);
        if (CheckUtil.collectionIsEmpty(list)) {
            throw PangException.create(EErrorCode.unData);
        }
        return list;
    }

    //根据当前登录用户返回该用户能查询的运力
    private List<Long> getTokenUserOfDriverIds( TokenUser tokenUser){
        OaSysUserRoleRes userRoleRes = oaSysUserMapper.getUserRoleRes(tokenUser.getTokenUserId());
        if(CheckUtil.objIsEmpty(userRoleRes)){
            throw PangException.create(EErrorCode.nullData);
        }
        List<Long> driverIds = new ArrayList<>();
        if(userRoleRes.getOfficeId() != 1){ //不是总公司
            List<OaDUserInfo> oaDUserInfoList = new ArrayList<>();
            if(CheckUtil.objIsNotEmpty(userRoleRes.getRoleId())){ //roleId不为空则是供应商
                 oaDUserInfoList = oaDUserInfoMapper.selectDriverIdsByOfficeOrCity(userRoleRes.getOfficeId(),null);
            }else{
                oaDUserInfoList = oaDUserInfoMapper.selectDriverIdsByOfficeOrCity(null, userRoleRes.getCityCode());
            }
            if(CheckUtil.objIsEmpty(oaDUserInfoList)){
                return driverIds;
            }
            for (OaDUserInfo oaDUserInfo: oaDUserInfoList
            ) {
                driverIds.add(oaDUserInfo.getDriverId());
            }
            return driverIds;
        }else{
            //是总公司则查询所有
            List<OaDUserInfo> oaDUserInfoList = oaDUserInfoMapper.selectDriverIdsByOfficeOrCity(null, null);
            if(CheckUtil.objIsEmpty(oaDUserInfoList)){
                return driverIds;
            }
            for (OaDUserInfo oaDUserInfo: oaDUserInfoList
            ) {
                driverIds.add(oaDUserInfo.getDriverId());
            }
            return driverIds;
        }
    }


    /**
     * 根据司机
     * @param driverId
     * @return
     */
    @Override
    public Rv getDriverLicenseImgInfoById(Long driverId) {
        QueryWrapper<OaSysAuditEntry> auditEntryQueryWrapper = new QueryWrapper<>();
        auditEntryQueryWrapper.eq("driver_id",driverId);
        OaSysAuditEntry oaSysAuditEntry = oaSysAuditEntryMapper.selectOne(auditEntryQueryWrapper);
        return Rv.wrap(oaSysAuditEntry);
    }

    /**
     * 司机信息管理列表查询
     *
     * @param current       页面
     * @param cityCode      城市
     * @param officeId      部门ID
     * @param accountStatus 账号状态
     * @param driverPhone   手机号码
     * @param driverName    司机姓名
     * @param service       业务类型
     * @param vehicleTeam   车队
     * @param driverType    司机类型
     * @param vehNo         车牌号
     * @return
     */
    @Override
    public Rv getDriverManagementList(Integer current, Integer pageSize, String cityCode, Long officeId, String accountStatus, String driverPhone, String driverName,
                                      String service, String vehicleTeam, String driverType, String vehNo, Integer acceptancOrderStatus) {
        List<OaSysOffice> oaSysOffice = this.findOaSysOffice();
        PageDTO dto = new PageDTO();
        dto.setPage(Long.valueOf(current));
        dto.setLimit(Long.valueOf(pageSize));
        List<DriverUserInfo> driverLike = new ArrayList<>();
        IPage iPage = new Page();
        List<Long> userIdList = new ArrayList<>();

        long userId = TokenUtil.getTokenUserId();
        List<Long> dusers;
        if (officeId == null) {
            //查找权限下可查看的所有司机
            dusers = oaSysGetOfficeIdListService.selectDUserIdList(userId, TokenUtil.getRoleDataScope());
        } else {
            //查找指定供应商管理的司机
            dusers = oaSysGetOfficeIdListService.selectDUserIdList(officeId);
        }
        if (dusers.size() == 0) {
            return Rv.wrap();
        }

        // 搜索城市
        if (CheckUtil.strIsNotEmpty(cityCode)) {
            QueryWrapper<OaDUserInfo> infoQueryWrapper = new QueryWrapper<>();
            infoQueryWrapper.select(OaDUserInfo.DRIVER_ID);
            infoQueryWrapper.eq(OaDUserInfo.DRIVER_CITY_ID, cityCode);
            infoQueryWrapper.in(OaDUserInfo.DRIVER_ID, dusers);

            List<OaDUserInfo> infoList = oaDUserInfoMapper.selectList(infoQueryWrapper);
            for (OaDUserInfo info : infoList) {
                userIdList.add(info.getDriverId());
            }
        } else {
            userIdList.addAll(dusers);
        }

        iPage.setSize(pageSize);
        iPage.setCurrent(current);
        driverLike = oaDUserMapper.getDriverManagementList(userIdList, service, dto.getIndex(), dto.getLimit(), accountStatus, driverPhone, driverName, driverType, vehNo, acceptancOrderStatus);
        Integer count = oaDUserMapper.getDriverManagementListCount(userIdList, service, accountStatus, driverPhone, driverName, driverType, vehNo, acceptancOrderStatus);
        // Integer count1 = oaDUserMapper.getDriverManagementListCountTest(userIdList,vehIdList,accountStatus, driverPhone, driverName, driverType, vehNo,acceptancOrderStatus);
        // 处理数据
        processing(driverLike);
        List<DriverUserInfo> resList = dataSplicing(driverLike, oaSysOffice);
        iPage.setRecords(resList);
        iPage.setTotal(count);
        return Rv.wrap(EErrorCode.success, iPage);
    }


    public void processing(List<DriverUserInfo> driverLike) {
        QueryWrapper<OaSysArea> areaQueryWrapper = new QueryWrapper<>();
        areaQueryWrapper.select(OaSysArea.NAME, OaSysArea.AD_CODE);
        List<OaSysArea> areaList = oaSysAreaMapper.selectList(areaQueryWrapper);
        QueryWrapper<OaDUserOffice> officeQueryWrapper = new QueryWrapper<>();
        officeQueryWrapper.select(OaDUserOffice.OFFICE_ID, OaDUserOffice.DRIVER_ID);
        List<OaDUserOffice> officeList = oaDUserOfficeMapper.selectList(officeQueryWrapper);

        for (DriverUserInfo like : driverLike) {
            for (OaDUserOffice office : officeList) {
                if (like.getDriverId().equals(office.getDriverId())) {
                    like.setOfficeId(office.getOfficeId());
                    break;
                }
            }
            if (CheckUtil.objIsNotEmpty(like.getDriverCityId())) {
                for (OaSysArea area : areaList) {
                    if (CheckUtil.objIsNotEmpty(like.getDriverCityId())) {
                        if (like.getDriverCityId().equals(area.getAdCode())) {
                            like.setCityName(area.getName());
                            break;
                        }
                    }
                }
            }
            if (CheckUtil.objIsNotEmpty(like.getDriverType())) {
                like.setDriverTypeStr(EOaDUserDriverType.findById(like.getDriverType()).getDesc());
            }
            if (CheckUtil.objIsNotEmpty(like.getVehType())) {
                like.setVehTypeStr(EvehicleType.findById(like.getVehType()).getValue());
            }
            if (CheckUtil.objIsNotEmpty(like.getSex())) {
                like.setSexStr(ESexType.findById(like.getSex()).getValue());
            }
            if (CheckUtil.objIsNotEmpty(like.getCreateTime())) {
                like.setCreateTimeStr(DateFormatUtils.format(like.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            }
            if (CheckUtil.objIsNotEmpty(like.getFirstLoginDate())) {
                like.setFirstLoginDateStr(DateFormatUtils.format(like.getFirstLoginDate(), "yyyy-MM-dd HH:mm:ss"));
            }
            if (CheckUtil.objIsNotEmpty(like.getCompleteFirstSingleDate())) {
                like.setCompleteFirstSingleDateStr(DateFormatUtils.format(like.getCompleteFirstSingleDate(), "yyyy-MM-dd HH:mm:ss"));
            }
            if (CheckUtil.objIsNotEmpty(like.getBirthday())) {
                like.setBirthdayStr(DateFormatUtils.format(like.getBirthday(), "yyyy-MM-dd"));
            }
            if (CheckUtil.objIsNotEmpty(like.getAcceptancOrderStatus())) {
                like.setAcceptancOrderStatusStr(EAcceptOrderType.findByIdShow(like.getAcceptancOrderStatus()).getValue());
            }
            like.setAccountStatusStr(EAccountStatusType.findById(like.getAccountStatus()).getValue());
        }
    }

    /**
     * 司机信息管理列表查询导出
     *
     * @param current       页面
     * @param cityCode      城市
     * @param accountStatus 账号状态
     * @param driverPhone   手机号码
     * @param driverName    司机姓名
     * @param service       业务类型
     * @param vehicleTeam   车队
     * @param driverType    司机类型
     * @param vehNo         车牌号
     * @return
     */
    @Override
    public Rv getDriverManagementListExport(Integer current, Integer pageSize, String cityCode, String accountStatus, String driverPhone, String driverName,
                                            String service, String vehicleTeam, String driverType, String vehNo, Integer acceptancOrderStatus) {
        List<DriverUserInfo> driverLike = new ArrayList<>();
        List<Long> userIdList = new ArrayList<>();
        // 搜索城市
        if (CheckUtil.strIsNotEmpty(cityCode)) {
            QueryWrapper<OaDUserInfo> infoQueryWrapper = new QueryWrapper<>();
            infoQueryWrapper.eq(OaDUserInfo.DRIVER_CITY_ID, cityCode);
            infoQueryWrapper.select(OaDUserInfo.DRIVER_ID);
            List<OaDUserInfo> infoList = oaDUserInfoMapper.selectList(infoQueryWrapper);
            for (OaDUserInfo info : infoList) {
                userIdList.add(info.getDriverId());
            }
        }
        driverLike = oaDUserMapper.getExportDriverManagementList(userIdList, service, accountStatus, driverPhone, driverName, driverType, vehNo, acceptancOrderStatus);
        processing(driverLike);
        return Rv.wrap(EErrorCode.success, driverLike);
    }

    /**
     * 获取司机列表页面模糊下拉选
     *
     * @return
     */
    @Override
    public Rv getSelectList() {
        QueryWrapper<OaSysDict> queryBusinessDict = new QueryWrapper<>();
        queryBusinessDict.eq(OaSysDict.TYPE, "require_level");
        List<OaSysDict> businessList = oaSysDictMapper.selectList(queryBusinessDict);

        QueryWrapper<OaSysDict> queryAccountDict = new QueryWrapper<>();
        queryAccountDict.eq(OaSysDict.TYPE, "account_status");
        List<OaSysDict> accountList = oaSysDictMapper.selectList(queryAccountDict);

        QueryWrapper<OaSysDict> queryDriverDict = new QueryWrapper<>();
        queryDriverDict.eq(OaSysDict.TYPE, "driver_type");
        List<OaSysDict> driverList = oaSysDictMapper.selectList(queryDriverDict);

        QueryWrapper<OaSysDict> queryTypeDict = new QueryWrapper<>();
        queryTypeDict.eq(OaSysDict.TYPE, "cancel_reason");
        List<OaSysDict> orderCancelList = oaSysDictMapper.selectList(queryTypeDict);

        QueryWrapper<OaSysDict> querycChannelDict = new QueryWrapper<>();
        querycChannelDict.eq(OaSysDict.TYPE, "order_channel");
        List<OaSysDict> channelList = oaSysDictMapper.selectList(querycChannelDict);

        QueryWrapper<OaSysDict> querycModuleDict = new QueryWrapper<>();
        querycModuleDict.eq(OaSysDict.TYPE, "business_module");
        List<OaSysDict> moduleList = oaSysDictMapper.selectList(querycModuleDict);

        QueryWrapper queryWrapperDict = new QueryWrapper();
        queryWrapperDict.eq(OaSysDict.TYPE, "wallet_record_type");
        List<OaSysDict> dictList = oaSysDictMapper.selectList(queryWrapperDict);

        QueryWrapper queryWrapperOrderTye = new QueryWrapper();
        queryWrapperOrderTye.eq(OaSysArea.TYPE, "order_type");
        List orderTypelist = oaSysDictMapper.selectList(queryWrapperOrderTye);

        SearchDriverSelect select = new SearchDriverSelect();
        select.setCancelReasonList(orderCancelList);
        select.setModuleList(moduleList);
        select.setOrderChannelList(channelList);
        select.setAccountList(accountList);
        select.setBusinessList(businessList);
        select.setDriverList(driverList);
        select.setRecordTypeList(dictList);
        select.setOrderTypeList(orderTypelist);
        return Rv.wrap(EErrorCode.success, select);
    }

    /**
     * 查看司机详情
     *
     * @param driverId：司机Id
     * @return
     */
    @Override
    public Rv getDriverDetails(Long driverId) {
        QueryWrapper<OaSysArea> areaQueryWrapper = new QueryWrapper<>();
        List<OaSysArea> areaList = oaSysAreaMapper.selectList(areaQueryWrapper);
        DriverUserInfo driverDetails = new DriverUserInfo();
        if (CheckUtil.objIsEmpty(driverId)) {
            return Rv.wrap(EErrorCode.success, driverDetails);
        }
        driverDetails = oaDUserMapper.getDriverDetails(driverId);
        if (CheckUtil.objIsEmpty(driverDetails)) {
            return Rv.wrap(EErrorCode.success, driverDetails);
        }
        if (CheckUtil.objIsNotEmpty(driverDetails.getDriverCityId())) {
            for (OaSysArea area : areaList) {
                if (driverDetails.getDriverCityId().equals(area.getAdCode())) {
                    driverDetails.setCityName(area.getName());
                    break;
                }
            }
        }
        if (CheckUtil.objIsNotEmpty(driverDetails.getDriverType())) {
            driverDetails.setDriverTypeStr(EOaDUserDriverType.findById(driverDetails.getDriverType()).getDesc());
        }
        if (CheckUtil.objIsNotEmpty(driverDetails.getAccountStatus())) {
            driverDetails.setAccountStatusStr(EAccountStatusType.findById(driverDetails.getAccountStatus()).getValue());
        }
        if (CheckUtil.objIsNotEmpty(driverDetails.getSex())) {
            driverDetails.setSexStr(ESexType.findById(driverDetails.getSex()).getValue());
        }
        driverDetails.setAvatarUrl("");
        driverDetails.setDriveLicenseUrl("");
        driverDetails.setDriveOtherLicenseUrl("");
        driverDetails.setIdentityOtherUrl("");
        driverDetails.setIdentityPositiveUrl("");
        driverDetails.setProfessionalQualificationUrl("");
        driverDetails.setNationalityStr("");
        driverDetails.setVehTypeStr("");
        driverDetails.setCreateTimeStr(new DateToStringConverter().convert(driverDetails.getCreateTime()));
        driverDetails.setFirstLoginDateStr(new DateToStringConverter().convert(driverDetails.getFirstLoginDate()));
        driverDetails.setCompleteFirstSingleDateStr(new DateToStringConverter().convert(driverDetails.getCompleteFirstSingleDate()));
        driverDetails.setDriverStartDateStr(new DateToStringConverter().convert(driverDetails.getDriverStartDate()));
        driverDetails.setDriveLicenseDuedateStr(new DateToStringConverter().convert(driverDetails.getDriveLicenseDuedate()));
        driverDetails.setReleaseDateStr(new DateToStringConverter().convert(driverDetails.getReleaseDate()));
        driverDetails.setCertificateValidityPeriodStartDateStr(new DateToStringConverter().convert(driverDetails.getCertificateValidityPeriodStartDate()));
        if (CheckUtil.objIsNotEmpty(driverDetails.getVehType())) {
            driverDetails.setVehTypeStr(EvehicleType.findById(driverDetails.getVehType()).getValue());
        }
        if (CheckUtil.objIsNotEmpty(driverDetails.getBirthday())) {
            driverDetails.setBirthdayStr(DateFormatUtils.format(driverDetails.getBirthday(), "yyyy-MM-dd"));
        }
        if (CheckUtil.objIsNotEmpty(driverDetails.getCertificateValidityPeriodEndDate())) {
            driverDetails.setCertificateValidityPeriodEndDateStr(DateFormatUtils.format(driverDetails.getCertificateValidityPeriodEndDate(), "yyyy-MM-dd"));
        }
        //查询用户信息表
        QueryWrapper<OaSysDict> queryWrapperDict = new QueryWrapper<>();
        queryWrapperDict.eq(OaSysDict.TYPE, "nationality_type");
        queryWrapperDict.eq(OaSysDict.VALUE, driverDetails.getNationality());
        List<OaSysDict> dictList = oaSysDictMapper.selectList(queryWrapperDict);
        if (!dictList.isEmpty()) {
            driverDetails.setNationalityStr(dictList.get(0).getLabel());
        }
        // 民族
        return Rv.wrap(EErrorCode.success, driverDetails);
    }


    /**
     * 添加司机信息
     *
     * @param driverUserInfo：接收司机信息的实体类
     * @return
     */
    @Override
    public Rv addDriver(DriverUserInfo driverUserInfo) {
        //查询用户基础表
        QueryWrapper<OaDUser> queryWrapperOaDUser = new QueryWrapper<>();
        queryWrapperOaDUser.eq(OaDUser.DRIVER_PHONE, driverUserInfo.getDriverPhone());
        List<OaDUser> oaDUsers = oaDUserMapper.selectList(queryWrapperOaDUser);
        //查询用户信息表
        QueryWrapper<OaDUserInfo> queryWrapperOaDUserInfo = new QueryWrapper<>();
        queryWrapperOaDUserInfo.eq(OaDUserInfo.IDENTITY_NUMBER, driverUserInfo.getIdentityNumber());
        queryWrapperOaDUserInfo.or().eq(OaDUserInfo.DRIVE_LICENSE_NO, driverUserInfo.getDriveLicenseNo());
        List<OaDUserInfo> oaDUserInfoS = oaDUserInfoMapper.selectList(queryWrapperOaDUserInfo);
        if (oaDUsers.size() == 0 && oaDUserInfoS.size() == 0) {
            UserLoginResult userLoginResult = (UserLoginResult) TokenUtil.getTokenUserEntity(UserLoginResult.class);
            QueryWrapper<OaSysOffice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(OaSysOffice.OFFICE_ID, userLoginResult.getOfficeId());
            OaSysOffice oaSysOffice = oaSysOfficeMapper.selectOne(queryWrapper);
            String tag = TokenUtil.getTag();
            if (CheckUtil.objIsEmpty(tag)) {
                throw PangException.create(EErrorCode.missingAuthArgs);
            }
            long driverId = IDUtil.nextId();
            //用户基础表
            OaDUser oaDUser = new OaDUser();
            oaDUser.setDriverId(driverId);
            oaDUser.setDriverPhone(driverUserInfo.getDriverPhone());
            oaDUser.setLoginAccount(driverUserInfo.getLoginAccount());
            oaDUser.setDriverName(driverUserInfo.getDriverName());
            oaDUser.setSex(driverUserInfo.getSex());
            oaDUser.setTag(tag);
            oaDUser.setCreateUser(TokenUtil.getTokenUserId());
            oaDUser.setCreateTime(new Date());
            oaDUser.setUpdateTime(new Date());
            oaDUser.setAvatarFileId(driverUserInfo.getAvatarFileId());
            //用户信息表
            OaDUserInfo oaDUserInfo = new OaDUserInfo();
            oaDUserInfo.setEmergencyContact(driverUserInfo.getEmergencyContact());
            oaDUserInfo.setEmergencyMobile(driverUserInfo.getEmergencyMobile());
            oaDUserInfo.setEmergencyAddress(driverUserInfo.getEmergencyAddress());
            oaDUserInfo.setEmergencyAddress(driverUserInfo.getEmergencyAddress());
            oaDUserInfo.setInfoId(IDUtil.nextId());
            oaDUserInfo.setDriverId(driverId);
            oaDUserInfo.setAge(driverUserInfo.getAge());
            oaDUserInfo.setAddress(driverUserInfo.getAddress());
            oaDUserInfo.setIdentityNumber(driverUserInfo.getIdentityNumber());
            oaDUserInfo.setIdentityType(1);
            oaDUserInfo.setIdentityAddress(driverUserInfo.getIdentityAddress());
            oaDUserInfo.setDriveLicenseNo(driverUserInfo.getDriveLicenseNo());
            oaDUserInfo.setDriverType(driverUserInfo.getDriverType());
            oaDUserInfo.setCreateUser(TokenUtil.getTokenUserId());
            oaDUserInfo.setCreateTime(new Date());
            oaDUserInfo.setUpdateTime(new Date());
            oaDUserInfo.setTag(tag);
            oaDUserInfo.setTotalServiceScore(EServiceFraction.serviceFraction.getValue());
            oaDUserInfo.setIdentityPositiveFileId(driverUserInfo.getIdentityPositiveFileId());
            oaDUserInfo.setIdentityOtherFileId(driverUserInfo.getIdentityOtherFileId());
            oaDUserInfo.setDriveLicenseFileId(driverUserInfo.getDriveLicenseFileId());
            oaDUserInfo.setDriveOtherLicenseFileId(driverUserInfo.getDriveOtherLicenseFileId());
            List<OaSysGlobalConfig> oaSysGlobalConfigs = oaSysGlobalConfigMapper.selectList(Wrappers.<OaSysGlobalConfig>lambdaQuery().eq(OaSysGlobalConfig::getTag, tag));
            if (oaSysGlobalConfigs.size() == 1) {
                if (CheckUtil.objIsNotEmpty(oaSysGlobalConfigs.get(0).getGouldServiceId())) {
                    AmapTidParam amapTidParam = new AmapTidParam();
                    amapTidParam.setClientId(TokenUtil.getClientId());
                    amapTidParam.setServiceId(oaSysGlobalConfigs.get(0).getGouldServiceId().toString());
                    amapTidParam.setTag(tag);
                    amapTidParam.setUserId(driverId);
                    Long sid = iAmapService.getAmapTid(amapTidParam);
                    oaDUserInfo.setTid(sid);
                }
            }
            //司机钱包表
            OaDWallet oaDWallet = new OaDWallet();
            oaDWallet.setWalletId(IDUtil.nextId());
            oaDWallet.setDriverId(driverId);
            oaDWallet.setTag(tag);
            oaDWallet.setOfficeId(userLoginResult.getOfficeId());
            oaDWallet.setWalletBalance(new BigDecimal(0));
            oaDWallet.setDeptOfficialBalance(new BigDecimal(0));
            oaDWallet.setCreateUser(TokenUtil.getTokenUserId());
            oaDWallet.setCreateTime(new Date());
            oaDWallet.setUpdateTime(new Date());
            //开始执行插入操作
            oaDUserMapper.insert(oaDUser);
            oaDUserInfoMapper.insert(oaDUserInfo);
            oaDWalletMapper.insert(oaDWallet);
            // 新增司机机构关联
            this.insertOaDUserOffice(driverUserInfo, driverId, userLoginResult, tag);
            return Rv.wrap(EErrorCode.success);
        } else {
            return Rv.wrap(EErrorCode.beUsed.getValue());
        }
    }

    /**
     * 修改司机信息
     *
     * @param driverUserInfo：接收司机信息的实体类
     * @return
     */
    @Override
    public Rv updateDriver(DriverUserInfo driverUserInfo) {
        Date date = new Date();
        String tag = TokenUtil.getTag();
        if (CheckUtil.objIsEmpty(tag)) {
            throw PangException.create(EErrorCode.missingAuthArgs);
        }
        //查询基础表
        QueryWrapper<OaDUser> queryWrapperOaDUser = new QueryWrapper<>();
        queryWrapperOaDUser.ne(OaDUser.DRIVER_ID, driverUserInfo.getDriverId());
        queryWrapperOaDUser.eq(OaDUser.DRIVER_PHONE, driverUserInfo.getDriverPhone());
        List<OaDUser> oaDUsers = oaDUserMapper.selectList(queryWrapperOaDUser);
        //查询用户表
        QueryWrapper<OaDUserInfo> queryWrapperOaDUserInfo = new QueryWrapper<>();
        queryWrapperOaDUserInfo.ne(OaDUserInfo.INFO_ID, driverUserInfo.getInfoId());
        queryWrapperOaDUserInfo.eq(OaDUserInfo.IDENTITY_NUMBER, driverUserInfo.getIdentityNumber());
        List<OaDUserInfo> oaDUserInfos = oaDUserInfoMapper.selectList(queryWrapperOaDUserInfo);
        //查询用户表
        QueryWrapper<OaDUserInfo> queryWrapperDUserInfo = new QueryWrapper<>();
        queryWrapperDUserInfo.ne(OaDUserInfo.INFO_ID, driverUserInfo.getInfoId());
        queryWrapperDUserInfo.eq(OaDUserInfo.DRIVE_LICENSE_NO, driverUserInfo.getDriveLicenseNo());
        List<OaDUserInfo> userInfos = oaDUserInfoMapper.selectList(queryWrapperDUserInfo);
        if (CheckUtil.objIsEmpty(oaDUsers) && CheckUtil.objIsEmpty(oaDUserInfos) && CheckUtil.objIsEmpty(userInfos)) {
            OaDUserInfo info = oaDUserInfoMapper.selectById(driverUserInfo.getInfoId());
            OaDUser dUser = oaDUserMapper.selectById(driverUserInfo.getDriverId());
            OaDUser oaDUser = new OaDUser();
            oaDUser.setDriverId(driverUserInfo.getDriverId());
            // 接单不能修改手机号
            if (info.getAcceptancOrderStatus() == 1 && !driverUserInfo.getDriverPhone().equals(dUser.getDriverPhone())) {
                throw PangException.create(EErrorCode.intOrderError);
            }
            oaDUser.setDriverPhone(driverUserInfo.getDriverPhone());
            oaDUser.setLoginAccount(driverUserInfo.getDriverPhone());
            oaDUser.setDriverName(driverUserInfo.getDriverName());
            oaDUser.setSex(driverUserInfo.getSex());
            oaDUser.setUpdateUser(TokenUtil.getTokenUserId());
            oaDUser.setUpdateTime(date);
            oaDUser.setUpdateUser(TokenUtil.getTokenUserId());
            oaDUser.setAccountStatus(driverUserInfo.getAccountStatus());
            info.setIdentityNumber(driverUserInfo.getIdentityNumber());
            info.setBirthday(driverUserInfo.getBirthday());
            info.setUpdateTime(date);
            info.setUpdateUser(TokenUtil.getTokenUserId());
            info.setDriveLicenseFileId(driverUserInfo.getDriveLicenseFileId());
            info.setDriveOtherLicenseFileId(driverUserInfo.getDriveOtherLicenseFileId());
            info.setIdentityPositiveFileId(driverUserInfo.getIdentityPositiveFileId());
            info.setIdentityOtherFileId(driverUserInfo.getIdentityOtherFileId());
            info.setProfessionalQualificationFileId(driverUserInfo.getProfessionalQualificationFileId());
            info.setProfessionalQualificationNumber(driverUserInfo.getProfessionalQualificationNumber());
            info.setVehicleTeam(driverUserInfo.getVehicleTeam());
            info.setGetDriverLicenseDate(driverUserInfo.getDriverStartDate());
            info.setTaxiDriver(driverUserInfo.getTaxiDriver());
            info.setNetWorkCarIssueOrGanization(driverUserInfo.getNetWorkCarIssueOrGanization());
            info.setGetNetWorkCarProofDate(driverUserInfo.getNetWorkCarProofOn());
            info.setNetWorkCarProofOn(driverUserInfo.getNetWorkCarProofOn());
            info.setNetWorkCarProofOff(driverUserInfo.getNetWorkCarProofOff());
            info.setRegisterDate(driverUserInfo.getRegisterDate());
            info.setContractCompany(driverUserInfo.getContractCompany());
            info.setContractOn(driverUserInfo.getContractOn());
            info.setContractOff(driverUserInfo.getContractOff());
            info.setNationality(driverUserInfo.getNationality());
            info.setDriverStartDate(driverUserInfo.getDriverStartDate());
            info.setDriveLicenseDuedate(driverUserInfo.getDriveLicenseDuedate());
            oaDUserMapper.updateById(oaDUser);
            oaDUserInfoMapper.updateById(info);
            // 修改司机信息关联
//            Long officeId = driverUserInfo.getOfficeId();
//            Long driverId = driverUserInfo.getDriverId();
//            Long sysUserId = TokenUtil.getTokenUserId();
//            if (CheckUtil.objIsNotEmpty(officeId, driverId)){
//                List<OaDUserOffice> oaDUserOffices = oaDUserOfficeMapper.selectList(
//                        Wrappers.<OaDUserOffice>lambdaQuery()
//                                .eq(OaDUserOffice::getTag, tag)
//                                .eq(OaDUserOffice::getDriverId, driverId));
//                if (oaDUserOffices.size() == 1){
//                    OaDUserOffice oaDUserOffice = oaDUserOffices.get(0);
//                    oaDUserOffice.setUpdateTime(date);
//                    oaDUserOffice.setUpdateUser(sysUserId);
//                    oaDUserOffice.setOfficeId(officeId);
//                    oaDUserOfficeMapper.updateById(oaDUserOffice);
//                }
//            }
            if(driverUserInfo.getVehNo() == null){
                Rv.error(EErrorCode.missingArg);
            }
            //查询车辆信息表
            QueryWrapper<OaSysVehicle> queryWrapperOSysVehicle = new QueryWrapper<>();
            queryWrapperOSysVehicle.eq(OaSysVehicle.VEH_NO,driverUserInfo.getVehNo());
            OaSysVehicle oaSysVehicle = oaSysVehicleMapper.selectOne(queryWrapperOSysVehicle);
            if (oaSysVehicle == null){
                Rv.error(EErrorCode.unDriverVehicle);
            }
            oaSysVehicle.setVehType(driverUserInfo.getVehType());
            oaSysVehicleMapper.updateById(oaSysVehicle);

            return Rv.wrap(EErrorCode.success);
        } else {
            return Rv.wrap(EErrorCode.beUsed.getValue());
        }
    }

    /**
     * 删除司机信息
     *
     * @param driverUserInfo：接收司机信息的实体类
     * @return
     */
    @Override
    public Rv deleteDriver(DriverUserInfo driverUserInfo) {
        OaDUser oaDUser = new OaDUser();
        oaDUser.setDriverId(driverUserInfo.getDriverId());
        oaDUser.setDeleted(1);
        oaDUserMapper.updateById(oaDUser);
        return Rv.wrap(EErrorCode.success);
    }

    /**
     * 获取司机车辆关联管理信息
     *
     * @return
     */
    @Override
    public Rv getDriverVehicle(Integer current) {
        IPage iPage = new Page();
        iPage.setCurrent(current);
        iPage.setSize(20);
        List<DriverVehicleInfo> driverVehicle = oaDDriverVehicleMapper.getDriverVehicle(iPage);
        iPage.setRecords(driverVehicle);
        return Rv.wrap(EErrorCode.success, iPage);
    }

    /**
     * 模糊查询获取司机车辆关联管理信息
     *
     * @param current:需要查询的页码
     * @param driverOnlineStatus:司机在线状态（0：在线、1：下在线线）
     * @param isUse:是否正在使用(0：否、1：是）
     * @param driverPhone:手机号码
     * @param driverName:用户姓名
     * @return
     */
    @Override
    public Rv getDriverVehicleLike(Integer current, String driverOnlineStatus, String isUse, String driverPhone, String driverName) {
        IPage iPage = new Page(current, 20);
        List<DriverVehicleInfo> driverVehicleLike = oaDDriverVehicleMapper.getDriverVehicleLike(iPage, driverOnlineStatus, isUse, driverPhone, driverName);
        iPage.setRecords(driverVehicleLike);
        return Rv.wrap(EErrorCode.success, iPage);
    }

    /**
     * 查询数据字典
     *
     * @return
     */
    private List<OaSysOffice> findOaSysOffice() {
        //查询车字典数据
        QueryWrapper<OaSysOffice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        return oaSysOfficeMapper.selectList(queryWrapper);
    }

    /**
     * 数据拼接表格
     *
     * @param driverUserInfos:用户List
     * @param oaSysOfficeList：字典List
     * @return
     */
    private List<DriverUserInfo> dataSplicing(List<DriverUserInfo> driverUserInfos, List<OaSysOffice> oaSysOfficeList) {
        for (int i = 0; i < driverUserInfos.size(); i++) {
            for (int j = 0; j < oaSysOfficeList.size(); j++) {
                if (CheckUtil.objIsNotEmpty(driverUserInfos.get(i).getOfficeId(), oaSysOfficeList.get(j).getOfficeId())) {
                    if (driverUserInfos.get(i).getOfficeId().longValue() == oaSysOfficeList.get(j).getOfficeId().longValue()) {
                        driverUserInfos.get(i).setDepartmentsOfAttribution(oaSysOfficeList.get(j).getName());
                        driverUserInfos.get(i).setOfficeCode(oaSysOfficeList.get(j).getCode());
                        for (int k = 0; k < oaSysOfficeList.size(); k++) {
                            if (String.valueOf(oaSysOfficeList.get(k).getOfficeId()).equals(oaSysOfficeList.get(j).getParentId())) {
                                driverUserInfos.get(i).setOwnershipCompany(oaSysOfficeList.get(k).getName());
                                break;
                            }
                        }
                        break;
                    }
                }
            }
        }
        return driverUserInfos;
    }

    /**
     * 新增司机机构关联
     *
     * @param driverUserInfo  入参实体
     * @param driverId        司机id
     * @param userLoginResult 当前登录人信息
     * @param tag             用户来源
     */
    private void insertOaDUserOffice(DriverUserInfo driverUserInfo, Long driverId, UserLoginResult userLoginResult, String tag) {
        Date date = new Date();
        Long sysUserId = TokenUtil.getTokenUserId();
        Long officeId = driverUserInfo.getOfficeId();
        OaDUserOffice oaDUserOffice = new OaDUserOffice();
        if (CheckUtil.objIsEmpty(officeId)) {
            oaDUserOffice.setOfficeId(userLoginResult.getOfficeId());
        } else {
            oaDUserOffice.setOfficeId(officeId);
        }
        oaDUserOffice.setLinkedId(IDUtil.nextId());
        oaDUserOffice.setDriverId(driverId);
        oaDUserOffice.setTag(tag);
        oaDUserOffice.setCreateUser(sysUserId);
        oaDUserOffice.setCreateTime(date);
        oaDUserOffice.setUpdateUser(sysUserId);
        oaDUserOffice.setUpdateTime(date);
        oaDUserOfficeMapper.insert(oaDUserOffice);
    }

    /**
     * 获取下载模板数据
     *
     * @return
     */
    @Override
    public Rv getDriverDownloadTemplate() {
        List<OaSysGlobalConfig> oaSysGlobalConfigs = sysGlobalConfigMapper.selectList(null);
        if (CheckUtil.objIsEmpty(oaSysGlobalConfigs)) {
            return Rv.wrap(EErrorCode.unData);
        }
        OaSysGlobalConfig config = oaSysGlobalConfigs.get(0);
        Map<String, Long> map = new HashMap<>();
        map.put("id", config.getDriverImportFileId());
        return Rv.wrap(EErrorCode.success, map);
    }

    /**
     * 更换车辆查询
     *
     * @return
     */
    @Override
    public Rv getChangeVehicleList(Integer current, Integer size, String vehNo) {
        if (CheckUtil.objIsEmpty(current, size)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        List<VehicleManageInfo> infoList = new ArrayList<>();
        // 设置分页信息
        IPage iPage = new Page();
        iPage.setCurrent(current);
        iPage.setSize(size);
        List<VehicleManageInfo> vehicleList = oaSysVehicleMapper.changeVehicleList(iPage, vehNo);
        if (vehicleList.isEmpty()) {
            iPage.setRecords(infoList);
            return Rv.wrap(EErrorCode.success, iPage);
        }
        infoList = this.getInfoList(vehicleList);
        iPage.setRecords(infoList);
        return Rv.wrap(EErrorCode.success, iPage);
    }

    private List<VehicleManageInfo> getInfoList(List<VehicleManageInfo> vehicleList) {
        // 车辆code码List
        List<String> vehicleCodeList = new ArrayList<>();
        for (int i = 0; i < vehicleList.size(); i++) {
            vehicleCodeList.add(vehicleList.get(i).getCode());
        }
        // 车辆字典表里查询到的3级车辆信息
        List<OaSysVehicleMdict> oaSysVehicleMdictsC = this.findVehicleMdict(vehicleCodeList, OaSysVehicleMdict.CODE);
        if (CheckUtil.objIsEmpty(oaSysVehicleMdictsC)) {
            return vehicleList;
        }
        // 装载二级菜单的List
        List<String> parentIdVehicleB = new ArrayList<>();
        for (int i = 0; i < oaSysVehicleMdictsC.size(); i++) {
            parentIdVehicleB.add(oaSysVehicleMdictsC.get(i).getParentId());
        }
        //车辆字典表里查询到的2级车辆信息
        List<OaSysVehicleMdict> oaSysVehicleMdictsB = this.findVehicleMdict(parentIdVehicleB, OaSysVehicleMdict.MDICT_ID);
        // 装载一级菜单的List
        List<String> parentIdVehicleA = new ArrayList<>();
        for (int i = 0; i < oaSysVehicleMdictsB.size(); i++) {
            parentIdVehicleA.add(oaSysVehicleMdictsB.get(i).getParentId());
        }
        // 车辆字典表里查询到的1级车辆信息
        List<OaSysVehicleMdict> oaSysVehicleMdictsA = this.findVehicleMdict(parentIdVehicleA, OaSysVehicleMdict.MDICT_ID);
        JSONArray oaSysVehicleMdictsCJSONArray = JSONArray.parseArray(JSON.toJSONString(oaSysVehicleMdictsC));
        JSONArray oaSysVehicleMdictsBJSONArray = JSONArray.parseArray(JSON.toJSONString(oaSysVehicleMdictsB));
        JSONArray oaSysVehicleMdictsAJSONArray = JSONArray.parseArray(JSON.toJSONString(oaSysVehicleMdictsA));
        JSONArray splicingData = VehicleManageServiceImpl.getVehicleSplicingData(
                oaSysVehicleMdictsAJSONArray, oaSysVehicleMdictsBJSONArray, oaSysVehicleMdictsCJSONArray,
                "vehicleCode1", "vehicleCode2", "vehicleCode3",
                "brand", "model", "vehicleTypeName",
                "code", "mdictId"
        );
        for (int i = 0; i < vehicleList.size(); i++) {
            for (int j = 0; j < splicingData.size(); j++) {
                if (CheckUtil.strIsNotEmpty(vehicleList.get(i).getCode()) && vehicleList.get(i).getCode().equals(splicingData.getJSONObject(j).getString("code"))) {
                    vehicleList.get(i).setModel(splicingData.getJSONObject(j).getString("model"));
                    vehicleList.get(i).setBrand(splicingData.getJSONObject(j).getString("brand"));
                    vehicleList.get(i).setVehicleTypeName(splicingData.getJSONObject(j).getString("vehicleTypeName"));
                    vehicleList.get(i).setVehicleCodeClassA(splicingData.getJSONObject(j).getString("vehicleCode1"));
                    vehicleList.get(i).setVehicleCodeClassB(splicingData.getJSONObject(j).getString("vehicleCode2"));
                    vehicleList.get(i).setVehicleCodeClassC(splicingData.getJSONObject(j).getString("vehicleCode3"));
                }
            }
        }
        return vehicleList;
    }

    /**
     * 查询车字典
     *
     * @return
     */
    private List<OaSysVehicleMdict> findVehicleMdict(List<String> inList, String findField) {
        //查询车字典数据
        QueryWrapper<OaSysVehicleMdict> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(findField, inList);
        queryWrapper.select(OaSysVehicleMdict.MDICT_ID, OaSysVehicleMdict.PARENT_ID, OaSysVehicleMdict.CODE, OaSysVehicleMdict.NAME);
        return oaSysVehicleMdictMapper.selectList(queryWrapper);
    }

    /**
     * 更换车辆
     *
     * @return
     */
    @Override
    public Rv getChangeVehicle(Long driverId, Long vehicleId) {
        if (CheckUtil.objIsEmpty(driverId, vehicleId)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        OaDDriverVehicle driverVehicle = oaDDriverVehicleMapper.selectOne(
                Wrappers.<OaDDriverVehicle>lambdaQuery()
                        .eq(OaDDriverVehicle::getDriverId, driverId));
        OaSysVehicle vehicle = oaSysVehicleMapper.selectById(vehicleId);
        if (CheckUtil.objIsEmpty(driverVehicle, vehicle)) {
            throw PangException.create(EErrorCode.unData);
        }
        Date date = new Date();
        Long vehicleOldId = driverVehicle.getVehicleId();
        driverVehicle.setVehicleId(vehicleId);
        driverVehicle.setUpdateTime(date);
        driverVehicle.setUpdateUser(TokenUtil.getTokenUserId());
        oaDDriverVehicleMapper.updateById(driverVehicle);
        vehicle.setVehicleOwnerId(driverId);
        vehicle.setUpdateTime(date);
        vehicle.setUpdateUser(TokenUtil.getTokenUserId());
        oaSysVehicleMapper.updateById(vehicle);
        OaSysVehicle oldVehicle = oaSysVehicleMapper.selectById(vehicleOldId);
        if (CheckUtil.objIsNotEmpty(oldVehicle)) {
            oldVehicle.setVehicleOwnerId(0L);
            oldVehicle.setUpdateTime(date);
            oldVehicle.setUpdateUser(TokenUtil.getTokenUserId());
            oaSysVehicleMapper.updateById(oldVehicle);
        }
        OaDDriverVehicle oldDVehicle = oaDDriverVehicleMapper.selectOne(
                Wrappers.<OaDDriverVehicle>lambdaQuery()
                        .eq(OaDDriverVehicle::getVehicleId, vehicleOldId));
        if (CheckUtil.objIsNotEmpty(oldDVehicle)) {
            oldDVehicle.setVehicleId(0L);
            oldDVehicle.setUpdateTime(date);
            oldDVehicle.setUpdateUser(TokenUtil.getTokenUserId());
            oaDDriverVehicleMapper.updateById(oldDVehicle);
        }
        return Rv.wrap(EErrorCode.success);
    }

    /**
     * 解绑车辆
     *
     * @return
     */
    @Override
    public Rv getUnbindVehicle(Long driverId) {
        if (CheckUtil.objIsEmpty(driverId)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        QueryWrapper<OaDUserInfo> infoQueryWrapper = new QueryWrapper<>();
        infoQueryWrapper.eq(OaDUserInfo.ACCEPTANC_ORDER_STATUS, 1);
        infoQueryWrapper.eq(OaDUserInfo.DRIVER_ID, driverId);
        List<OaDUserInfo> infoList = oaDUserInfoMapper.selectList(infoQueryWrapper);
        if (!infoList.isEmpty()) {
            throw PangException.create(EErrorCode.receivingOrderCar);
        }
        OaDDriverVehicle driverVehicle = oaDDriverVehicleMapper.selectOne(
                Wrappers.<OaDDriverVehicle>lambdaQuery()
                        .eq(OaDDriverVehicle::getDriverId, driverId));
        if (CheckUtil.objIsEmpty(driverVehicle)) {
            throw PangException.create(EErrorCode.unData);
        }
        OaSysVehicle vehicle = oaSysVehicleMapper.selectById(driverVehicle.getVehicleId());
        Date date = new Date();
        driverVehicle.setVehicleId(0L);
        driverVehicle.setUpdateTime(date);
        driverVehicle.setUpdateUser(TokenUtil.getTokenUserId());
        oaDDriverVehicleMapper.updateById(driverVehicle);
        if (CheckUtil.objIsNotEmpty(vehicle)) {
            vehicle.setUpdateTime(date);
            vehicle.setVehicleOwnerId(0L);
            vehicle.setUpdateUser(TokenUtil.getTokenUserId());
            oaSysVehicleMapper.updateById(vehicle);
        }
        return Rv.wrap(EErrorCode.success);
    }



    /**
     * 距离计算，请参考下面代码
     * @param lng1
     * @param lat1
     * @param lng2
     * @param lat2
     * @return 米
     */
    public static double getDistance(double lng1,double lat1,double lng2,double lat2){
        double radLat1 = Math.toRadians(lat1);
        double radLat2 = Math.toRadians(lat2);
        double a = radLat1 - radLat2;
        double b = Math.toRadians(lng1) - Math.toRadians(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1)
                * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378137.0;// 取WGS84标准参考椭球中的地球长半径(单位:m)
        s = Math.round(s * 10000) / 10000;
        return s;
    }
    //开发者测试距离
    public static void main(String[] args) {
        int v=1;
        int time=0;
        int result=0;
        while (true){
            result=2*result+1;
            time++;
            if (result>1000000){
                System.out.println("循环 "+time+" ,数据量为："+result);
                break;
            }
        }
    }

}
